const { app, Menu, Tray, BrowserWindow } = require('electron');
const { join, dirname } = require('path');

const { GLOBAL_APP_NAME } = require('./config');

const isWin = process.platform === 'win32';

let tray = null;
function createTray() {
    app.whenReady().then(() => {
        const iconPath = createIconPath();
        tray = new Tray(iconPath);
        const contextMenu = Menu.buildFromTemplate([
            {
                label: '显示',
                click() {
                    show();
                }
            },
            {
                label: '退出',
                click() {
                    if (isWin) {
                        global.mainWindow && global.mainWindow.destroy();
                    } else {
                        app.quit();
                    }
                }
            },
        ]);

        tray.on('double-click', () => {
            show();
        });

        tray.setToolTip(GLOBAL_APP_NAME);
        tray.setContextMenu(contextMenu);
    });
}

function show() {
    global.mainWindow ? global.mainWindow.show() : global.createWindow();
}

function createIconPath() {
    let ipath = join(process.cwd());

    const ext = isWin ? 'ico' : 'png';
    if (process.env.NODE_ENV != 'development' && !process.env.K_DEBUG) {
        ipath = isWin ? join(dirname(process.execPath), 'resources') : join(dirname(app.getAppPath()));
        return join(ipath, `icon.${ext}`);
    }

    return isWin ? join(ipath, `resources/${GLOBAL_APP_NAME}/icon.${ext}`)
        : join(ipath, 'resources', 'trays', 'osx', 'icon.png');
}

createTray();